package com.feijiang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.feijiang.entity.User;
import com.feijiang.mapper.UserMapper;
import com.feijiang.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feijiang.vo.UserVo;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2021-12-28
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
  @Resource
  UserMapper userMapper;

  @Override
  public User hasUser(User user) {
    QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
    userQueryWrapper.eq("username", user.getUsername());
    userQueryWrapper.eq("password", user.getPassword());
    List<User> userList = userMapper.selectList(userQueryWrapper);
    Assert.isTrue(userList.size() > 0, "用户名或密码错误");
    return userList.get(0);
  }

  @Override
  public Boolean selectById(int id) {
    User user = this.getById(id);
    return user != null;
  }

  @Override
  public Boolean register(User user) {
    if (usernameExist(user.getUsername())) {
      return false;
    }
    user.setRole("role");
    int insert = userMapper.insert(user);
    return insert > 0;
  }

  @Override
  public Boolean editPassword(UserVo userVo) {
    if (!checkPassword(userVo.getUsername(), userVo.getPassword())) {
      return false;
    }
    UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
    userUpdateWrapper.eq("username", userVo.getUsername());
    User user = new User();
    user.setPassword(userVo.getNewPassword());
    int i = userMapper.update(user, userUpdateWrapper);
    return i > 0;
  }

  private boolean usernameExist(String username) {
    QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
    userQueryWrapper.eq("username", username);
    List<User> userList = userMapper.selectList(userQueryWrapper);
    return userList.size() > 0;
  }

  private boolean checkPassword(String username, String password) {
    QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
    userQueryWrapper.eq("username", username);
    userQueryWrapper.eq("password", password);
    List<User> userList = userMapper.selectList(userQueryWrapper);
    return !CollectionUtils.isEmpty(userList);
  }
}
